"""
搜索服务
"""
from typing import List, Dict, Any, Optional
from .knowledge_base import KnowledgeBaseService


class SearchService:
    """搜索服务"""
    
    def __init__(self):
        self.knowledge_bases = {}
    
    def get_knowledge_base(self, kb_name: str) -> KnowledgeBaseService:
        """获取知识库实例"""
        if kb_name not in self.knowledge_bases:
            self.knowledge_bases[kb_name] = KnowledgeBaseService(kb_name)
        return self.knowledge_bases[kb_name]
    
    def search(
        self,
        query: str,
        kb_name: str = "default",
        top_k: int = None,
        score_threshold: float = None,
        **kwargs
    ) -> List[Dict[str, Any]]:
        """搜索相似文档"""
        kb = self.get_knowledge_base(kb_name)
        return kb.search(query, top_k, score_threshold, **kwargs)
    
    def search_multiple_kb(
        self,
        query: str,
        kb_names: List[str],
        top_k: int = None,
        score_threshold: float = None,
        **kwargs
    ) -> Dict[str, List[Dict[str, Any]]]:
        """在多个知识库中搜索"""
        results = {}
        for kb_name in kb_names:
            try:
                kb_results = self.search(query, kb_name, top_k, score_threshold, **kwargs)
                results[kb_name] = kb_results
            except Exception as e:
                results[kb_name] = []
                print(f"在知识库 {kb_name} 中搜索失败: {e}")
        
        return results
    
    def add_document(
        self,
        file_path: str,
        kb_name: str = "default",
        **kwargs
    ) -> Dict[str, Any]:
        """添加文档到知识库"""
        kb = self.get_knowledge_base(kb_name)
        return kb.add_document(file_path, **kwargs)
    
    def add_documents(
        self,
        file_paths: List[str],
        kb_name: str = "default",
        **kwargs
    ) -> List[Dict[str, Any]]:
        """批量添加文档到知识库"""
        kb = self.get_knowledge_base(kb_name)
        return kb.add_documents(file_paths, **kwargs)
    
    def delete_document(
        self,
        file_path: str,
        kb_name: str = "default"
    ) -> bool:
        """从知识库删除文档"""
        kb = self.get_knowledge_base(kb_name)
        return kb.delete_document(file_path)
    
    def clear_knowledge_base(self, kb_name: str = "default") -> bool:
        """清空知识库"""
        kb = self.get_knowledge_base(kb_name)
        return kb.clear()
    
    def get_knowledge_base_info(self, kb_name: str = "default") -> Dict[str, Any]:
        """获取知识库信息"""
        kb = self.get_knowledge_base(kb_name)
        return kb.get_info()
    
    def list_knowledge_bases(self) -> List[str]:
        """列出所有知识库"""
        return list(self.knowledge_bases.keys())
    
    def list_documents(self, kb_name: str = "default") -> List[Dict[str, Any]]:
        """列出知识库中的所有文档"""
        kb = self.get_knowledge_base(kb_name)
        return kb.list_documents() 